--[[
    Builder 地图打包 
]]
local map_filecategory = setmetatable({
    mdx = 'resource',
    mdl = 'resource',
    blp = 'resource',
    tga = 'resource',
    dds = 'resource',
    tif = 'resource',
    mp3 = 'sound',
    wav = 'sound',
},
{
    __index = function ()
        return 'map'
    end
}
)

local _mk_path = {}
local _mkdir = function ( root, path )
    if _mk_path[path:lower()] then
        return
    end

    mkdir(root .. '\\' .. path )

    path = path:lower()
    --创建多级目录时 将目录每一层都缓存节省创建时间
    while path ~= '' do
        _mk_path[ path ] = true

        path = path:sub2('\\', true)
    end
end

--分类文件: 将目录的 [资源文件] 复制到 [临时项目] 目录以便打包
---@param root string 结尾不带\的路径
function builder:sortFiles( root )
    local list = dir_list( root, true, '/a-d')
    local len = root:len() + 1
    local temp = self.temp


    for _, filename in pairs(list) do
        --相对路径(完整)
        filename = filename:a2u():sub(len+1)

        --文件名(不包括扩展名)
        local name = filename:sub( filename:find_r('\\') + 1, filename:find_r('.', true) - 1 )

        ---扩展名
        local extension = filename:sub( filename:find_r('.', true) + 1 ):lower()

        ---相对目录 末尾不带\
        local dir = filename:sub2('\\', true)

        ---分类
        local category = map_filecategory[extension]

        if category ~= 'map' then

            _mkdir(temp .. '\\' .. category, dir)

            copy(
                root .. '\\' .. dir .. '\\' .. name .. '.' .. extension,
                temp .. '\\'.. category ..'\\' .. dir .. '\\' .. name .. '.' .. extension
            )
        end
    end

end

function builder:packW3x()
    local input = Root .. '\\debug\\' ..  builder.map  .. '\\temp'
    local output = input:sub2('\\') .. os.date("[%Y-%m-%d] %H_%M_%S",os.time()) ..'.w3x'
    local build_type = 'obj'
    local env = Root .. '\\compiler\\Env\\'
    self.w3x_test = output --临时测试w3x地图文件
    local luac
    if self.type == 'slk' or self.type == 'obfuscation' then
        os.execute(  ('w3x2lni\\w2l.exe config %s=%s >nul'):format('slk.confused', self.type == 'obfuscation') )
        build_type = 'slk'
        env = env .. 'slk.lua'
        luac = mod:load("luac")
    elseif self.type == 'debug' then
        build_type = 'obj'
        env = env .. 'debug.lua'
    else
        build_type = 'obj'
        env = env .. 'test.lua'
    end

    copy(env, input ..'\\map\\xLua\\Env.lua')

    if self.type == 'debug' then
        require 'compile.debug'(self)    --debug处理
    end
    if luac then
        luac:encryption()
    end


    self:sortFiles( input .. '\\map' )

    --兼容没有该目录的旧项目
    mkdir(  self.path_map .. '\\res' )

    self:sortFiles( self.path_map .. '\\res' )


    local command = table.concat({
        "w3x2lni\\w2l.exe",
        build_type,
        '"' .. input .. '"',
        '"' .. output .. '"',
       '',
    },' ')
    print("[4]开始打包地图...")

    --显示进度
    local suc, stat, code = os.execute(command)

end
